package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.impl.CompanyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/getCompanyDetail")
public class GetManagerCompanyServlet extends HttpServlet {
    private final CompanyService companyService = new CompanyServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 首先检查是否有managerId参数
            String managerId = request.getParameter("managerId");
            
            // 如果没有managerId参数，则尝试从session获取当前用户的ID
            if (managerId == null || managerId.trim().isEmpty()) {
                HttpSession session = request.getSession(false);
                if (session != null && session.getAttribute("user") != null) {
                    User currentUser = (User) session.getAttribute("user");
                    managerId = currentUser.getId();
                }
            }
            
            // 如果managerId仍然为空，返回错误
            if (managerId == null || managerId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "未指定公司负责人ID");
                out.write(gson.toJson(result));
                return;
            }
            
            // 根据managerId获取公司信息
            Company company = companyService.getCompanyByManagerId(managerId);
            
            if (company == null) {
                result.put("success", false);
                result.put("message", "未找到公司信息");
            } else {
                result.put("success", true);
                result.put("company", company);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取公司信息失败：" + e.getMessage());
        }
        
        out.write(gson.toJson(result));
        out.flush();
    }
} 